<template>
  <div class="maintenance-evaluation">
    <el-card>
      <div slot="header" class="clearfix">
        <span>维护效果评估</span>
      </div>
      <el-tabs v-model="activeTab">
        <!-- 健康度追踪 -->
        <el-tab-pane label="健康度追踪" name="health">
          <div class="section">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-card>
                  <div class="title">设备健康评分</div>
                  <el-progress
                    :percentage="scoreBefore"
                    color="#f56c6c"
                    :text-inside="true"
                    :stroke-width="24"
                    style="margin-bottom: 10px;"
                  >
                  </el-progress>
                  <div>维护前评分：<b>{{ scoreBefore }}</b> 分</div>
                  <el-divider></el-divider>
                  <el-progress
                    :percentage="scoreAfter"
                    color="#67c23a"
                    :text-inside="true"
                    :stroke-width="24"
                  >
                  </el-progress>
                  <div>维护后评分：<b>{{ scoreAfter }}</b> 分</div>
                </el-card>
              </el-col>
              <el-col :span="12">
                <el-card>
                  <div class="title">自动采集倒计时</div>
                  <el-statistic
                    :value="countdown"
                    :title="'距离下次自动采集（72小时）'"
                    :precision="0"
                    suffix="秒"
                  />
                  <el-button
                    type="primary"
                    size="mini"
                    :disabled="countdown > 0"
                    @click="collectData"
                    style="margin-top: 10px;"
                  >立即采集</el-button>
                  <div v-if="lastCollectTime" style="margin-top: 10px; color: #909399;">
                    上次采集时间：{{ lastCollectTime }}
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>

        <!-- 故障复发 -->
        <el-tab-pane label="故障复发" name="recurrence">
          <div class="section">
            <el-card>
              <div class="title">30天内相同故障发生次数</div>
              <el-table :data="faults" style="width: 100%;">
                <el-table-column prop="date" label="日期" width="120"/>
                <el-table-column prop="fault" label="故障类型"/>
                <el-table-column prop="count" label="发生次数"/>
                <el-table-column
                  label="达标"
                  width="80"
                  :formatter="row => row.count <= 1 ? '✔' : '✘'"
                />
              </el-table>
              <div style="margin-top: 10px;">
                <el-tag
                  :type="totalRecurrence <= 1 ? 'success' : 'danger'"
                >{{ totalRecurrence <= 1 ? '达标' : '不达标' }}</el-tag>
                <span style="margin-left: 10px;">（要求≤1次，当前：{{ totalRecurrence }}次）</span>
              </div>
            </el-card>
          </div>
        </el-tab-pane>

        <!-- 策略优化 -->
        <el-tab-pane label="策略优化" name="optimize">
          <div class="section">
            <el-card>
              <div class="title">模型参数</div>
              <el-form :inline="true" label-width="120px">
                <el-form-item label="轴承故障预测阈值">
                  <el-input-number
                    v-model="modelParam"
                    :min="0"
                    :max="100"
                    :step="1"
                    :disabled="true"
                  />
                  <span style="margin-left: 10px;">分</span>
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    @click="optimizeStrategy"
                    :disabled="optimizeLoading"
                  >策略优化</el-button>
                </el-form-item>
              </el-form>
              <el-alert
                v-if="optimizeMsg"
                :title="optimizeMsg"
                type="success"
                show-icon
                style="margin-top: 10px;"
              />
            </el-card>
            <el-card style="margin-top: 20px;">
              <div class="title">历史优化记录</div>
              <el-table :data="optimizeLogs" style="width: 100%;">
                <el-table-column prop="date" label="时间" width="180"/>
                <el-table-column prop="oldValue" label="原阈值"/>
                <el-table-column prop="newValue" label="新阈值"/>
                <el-table-column prop="status" label="状态" width="120">
                  <template slot-scope="scope">
                    <el-tag :type="scope.row.applied ? 'success' : 'info'">
                      {{ scope.row.applied ? '已应用' : '未应用' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120">
                  <template slot-scope="scope">
                    <el-button
                      v-if="!scope.row.applied"
                      type="primary"
                      size="mini"
                      @click="applyOptimize(scope.$index)"
                    >应用</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'MaintenanceEffectEvaluation',
  data() {
    return {
      activeTab: 'health',
      // 健康度追踪
      scoreBefore: 35,
      scoreAfter: 85,
      countdown: 0,
      lastCollectTime: '',
      // 故障复发
      faults: [],
      // 策略优化
      modelParam: 70,
      optimizeLoading: false,
      optimizeMsg: '',
      optimizeLogs: []
    }
  },
  computed: {
    totalRecurrence() {
      // 统计30天内相同故障总次数
      return this.faults.reduce((sum, item) => sum + item.count, 0)
    }
  },
  created() {
    this.loadLocalData()
    this.initCountdown()
    this.mockFaults()
    this.mockOptimizeLogs()
  },
  methods: {
    // 本地数据加载
    loadLocalData() {
      // 评分
      const before = localStorage.getItem('scoreBefore')
      const after = localStorage.getItem('scoreAfter')
      if (before) this.scoreBefore = Number(before)
      if (after) this.scoreAfter = Number(after)
      // 模型参数
      const param = localStorage.getItem('modelParam')
      if (param) this.modelParam = Number(param)
      // 优化日志
      const logs = localStorage.getItem('optimizeLogs')
      if (logs) this.optimizeLogs = JSON.parse(logs)
      // 上次采集时间
      const last = localStorage.getItem('lastCollectTime')
      if (last) this.lastCollectTime = last
    },
    // 倒计时初始化
    initCountdown() {
      // 72小时 = 259200秒
      const last = localStorage.getItem('lastCollectTimestamp')
      const now = Date.now()
      let remain = 0
      if (last) {
        const diff = Math.floor((now - Number(last)) / 1000)
        remain = 259200 - diff
        if (remain < 0) remain = 0
      } else {
        remain = 0
      }
      this.countdown = remain
      if (remain > 0) {
        this.startCountdown()
      }
    },
    startCountdown() {
      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--
        } else {
          clearInterval(this.timer)
        }
      }, 1000)
    },
    collectData() {
      // 模拟采集后评分变化
      this.scoreBefore = this.scoreAfter
      this.scoreAfter = Math.min(100, this.scoreAfter + Math.floor(Math.random() * 10 + 1))
      localStorage.setItem('scoreBefore', this.scoreBefore)
      localStorage.setItem('scoreAfter', this.scoreAfter)
      // 记录采集时间
      const now = Date.now()
      this.lastCollectTime = this.formatDate(now)
      localStorage.setItem('lastCollectTime', this.lastCollectTime)
      localStorage.setItem('lastCollectTimestamp', now)
      this.countdown = 259200 // 72小时
      this.startCountdown()
      this.$message.success('数据采集成功，评分已更新')
    },
    // 故障复发模拟
    mockFaults() {
      // 生成30天内的模拟数据
      const today = new Date()
      const faults = []
      let total = 0
      for (let i = 0; i < 30; i++) {
        const date = new Date(today.getTime() - i * 24 * 3600 * 1000)
        const count = i === 5 ? 1 : 0 // 只在第5天有一次
        if (count > 0) total += count
        faults.push({
          date: this.formatDate(date),
          fault: '轴承故障',
          count
        })
      }
      this.faults = faults
    },
    // 优化日志模拟
    mockOptimizeLogs() {
      // 如果本地已有则不生成
      if (this.optimizeLogs.length) return
      this.optimizeLogs = []
    },
    // 策略优化
    optimizeStrategy() {
      this.optimizeLoading = true
      setTimeout(() => {
        const oldValue = this.modelParam
        const newValue = oldValue - 5
        this.modelParam = newValue
        localStorage.setItem('modelParam', newValue)
        // 记录日志
        const log = {
          date: this.formatDate(Date.now()),
          oldValue,
          newValue,
          applied: false
        }
        this.optimizeLogs.unshift(log)
        localStorage.setItem('optimizeLogs', JSON.stringify(this.optimizeLogs))
        this.optimizeMsg = `已自动将轴承故障预测阈值从${oldValue}分下调至${newValue}分`
        this.optimizeLoading = false
        setTimeout(() => {
          this.optimizeMsg = ''
        }, 3000)
      }, 1200)
    },
    // 应用优化
    applyOptimize(index) {
      const log = this.optimizeLogs[index]
      this.modelParam = log.newValue
      log.applied = true
      localStorage.setItem('modelParam', log.newValue)
      localStorage.setItem('optimizeLogs', JSON.stringify(this.optimizeLogs))
      this.$message.success('优化方案已应用')
    },
    // 日期格式化
    formatDate(ts) {
      const d = typeof ts === 'number' ? new Date(ts) : ts
      const y = d.getFullYear()
      const m = ('0' + (d.getMonth() + 1)).slice(-2)
      const day = ('0' + d.getDate()).slice(-2)
      const h = ('0' + d.getHours()).slice(-2)
      const min = ('0' + d.getMinutes()).slice(-2)
      const s = ('0' + d.getSeconds()).slice(-2)
      return `${y}-${m}-${day} ${h}:${min}:${s}`
    }
  },
  beforeDestroy() {
    if (this.timer) clearInterval(this.timer)
  }
}
</script>

<style scoped>
.maintenance-evaluation {
  padding: 20px;
}
.section {
  margin-bottom: 20px;
}
.title {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 10px;
}
</style>
